//
//  MultiSelectViewController.m
//  XieZB
//
//  Created by Sam on 16/10/25.
//  Copyright © 2016年 XieZB. All rights reserved.
//

#import "MultiSelectViewController.h"
#import "ViewUtils.h"
#import "UpImage.h"

@interface MultiSelectViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *pagingScrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, assign) CGPoint pageControlOffset;
@property (nonatomic, strong) NSMutableArray *scrollViewPages;
@property (nonatomic, strong) UIButton *cancelBtn,*uploadBtn,*switchButton;
@property (nonatomic, strong) NSArray *upImages;
@property (nonatomic, assign) NSInteger readCount;
@end

@implementation MultiSelectViewController

@synthesize pageControlOffset = _pageControlOffset;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setScroll];
    [self setPage];
    [self reloadPages];
    if(!self.toShow){
         [self addBtns];
    }else{
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
        [self.view addGestureRecognizer:tap];
    }
   
    
}

- (void)dismiss{
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)addBtns {
    
    self.cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelBtn.frame = CGRectMake(0, 0, 70.0f, 70.0f);
    self.cancelBtn.clipsToBounds = YES;
    [self.cancelBtn setTitle:@"删除" forState:UIControlStateNormal];
    self.cancelBtn.layer.cornerRadius = self.cancelBtn.width / 2.0f;
    self.cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.cancelBtn.backgroundColor = [[UIColor colorWithHexString:@"0xff6a3c"] colorWithAlphaComponent:0.5];
    self.cancelBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.cancelBtn.layer.shouldRasterize = YES;
    [self.cancelBtn addTarget:self action:@selector(deleteButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.cancelBtn];
    
    
    self.uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.uploadBtn.frame = CGRectMake(0, 0, 70.0f, 70.0f);
    self.uploadBtn.clipsToBounds = YES;
    [self.uploadBtn setTitle:@"全部上传" forState:UIControlStateNormal];
    self.uploadBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.uploadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.uploadBtn.layer.cornerRadius = self.uploadBtn.width / 2.0f;
    self.uploadBtn.backgroundColor = [UIColor colorWithHexString:kMainColor] ;
    self.uploadBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
    self.uploadBtn.layer.shouldRasterize = YES;
    [self.uploadBtn addTarget:self action:@selector(uploadButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.uploadBtn];
    
    
    
    self.switchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.switchButton.frame = CGRectMake(0, 0, 29.0f + 30.0f, 22.0f + 30.0f);
    self.switchButton.tintColor = [UIColor whiteColor];
    [self.switchButton setImage:[UIImage imageNamed:@"cancel.png"] forState:UIControlStateNormal];
    self.switchButton.imageEdgeInsets = UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f);
    [self.switchButton addTarget:self action:@selector(switchButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.switchButton];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = [UIColor clearColor];
    }
}

- (void)deleteButtonPressed {
    
    if(self.images.count == 1){
        self.images = [NSMutableArray array];
        if(self.deletBlock){
            self.deletBlock(self.images);
        }
         [self dismissViewControllerAnimated:NO completion:nil];
        return;
    }
    if(!self.pageControl.currentPage){
        self.pageControl.currentPage = 0;
    }
    [self.images removeObjectAtIndex:self.pageControl.currentPage];
    if(self.deletBlock){
        self.deletBlock(self.images);
    }
    [self resetScollViewPages];
    [self reloadPages];

}


- (void)uploadButtonPressed {
    
    self.upImages = [UpImage transferImages:self.images];
    self.readCount = 1;
    [self.view showProcess];
    [self nextResource];
    
}


- (void)nextResource {
    BOOL finish = YES;
    for(UpImage *image in self.upImages){
        if(![image.url hasPrefix:@"http"]){
            finish = NO;
            [self uploadPhoto:(UpImage *)image];
            break;
        }
    }
    
    if (finish ){
        
        //全部上传完毕
        [self.view showSuccess:@"上传完成"];
        [self dismissViewControllerAnimated:YES completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"UploadSuccess2" object:nil];
        
    }
}

- (void)uploadPhoto:(UpImage *)image{
    NSDictionary *param;

    param = @{
                @"exercise_uid":self.exerciseUid
                  };

    

    
    __weak typeof(self) weakSelf = self;
    
    [[XZBNetAPIClient sharedJsonClient] requestJsonDataWithPath:@"v1/pool/image/access" withParams:param withMethodType:Get andBlock:^(id responseData, NSError *error){
        
        if(!error){
            NSDictionary *data = [responseData objectForKey:@"data"];
            NSDictionary *uploadParams = @{
                                           @"key":[NSString stringWithFormat:@"%@%@-origin.jpg",[data objectForKey:@"dir"],[NSObject getUUID]],
                                           @"policy":[data objectForKey:@"policy"],
                                           @"OSSAccessKeyId":[data objectForKey:@"accessid"],
                                           @"signature":[data objectForKey:@"signature"]
                                           };
            
            NSLog(@"%@",uploadParams);
            [[XZBNetAPIClient sharedJsonClient] uploadImage:image.image path:[data objectForKey:@"host"] params:uploadParams successBlock:^(AFHTTPRequestOperation *operation , id responseObject){
     
                
                NSDictionary *syanParmas = @{
                                             @"uid":[NSObject getUUID],
                                             @"exercise_uid":weakSelf.exerciseUid
                                             };
                [[XZBNetAPIClient sharedJsonClient] requestJsonDataWithPath:@"v1/pool/image/access" withParams:syanParmas withMethodType:Post andBlock:^(id responseData, NSError *error){
                    if(!error){
                        
                        NSDictionary *data = [responseData objectForKey:@"data"];
                        image.url = [data objectForKey:@"url"];
                        weakSelf.readCount += 1;
                        NSString *p = [NSString stringWithFormat:@"图片上传中%ld/%lu",(long)weakSelf.readCount,(unsigned long)weakSelf.images.count];
                        CGFloat f = (CGFloat)weakSelf.readCount / (CGFloat)weakSelf.images.count;
                        [weakSelf.view showProcessWithStatus:p process:f];
                        [weakSelf nextResource];
                    }
                }];
                
                
            } failureBlock:^(AFHTTPRequestOperation *operation , NSError *error){
                [weakSelf.view hideProcess];
            } progerssBlock:^(CGFloat progressValue){
            }];
        }
    }];

}




- (void)switchButtonPressed:(UIButton *)button
{
    [self dismissViewControllerAnimated:NO completion:nil];
}


- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.cancelBtn.center = self.view.contentCenter;
    self.cancelBtn.bottom = self.view.height - 15.0f;
    self.cancelBtn.left = (self.view.width/4) - 35.0f;
    
    
    self.uploadBtn.center = self.view.contentCenter;
    self.uploadBtn.bottom = self.view.height - 15.0f;
    self.uploadBtn.right = (self.view.width*3/4) + 35.0f;
    
    
    self.switchButton.top = 3.0f;
    self.switchButton.right = self.view.width - 5.0f;
}

- (void)setPage {
    self.pageControl = [[UIPageControl alloc] initWithFrame:[self frameOfPageControl]];
    self.pageControl.pageIndicatorTintColor = [UIColor grayColor];
    self.pageControl.currentPage = 0;
    [self.view addSubview:self.pageControl];
}

- (void)setScroll {
    self.pagingScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.pagingScrollView.delegate = self;
    self.pagingScrollView.pagingEnabled = YES;
    self.pagingScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.pagingScrollView];
}


- (void)reloadPages
{
    self.pageControl.numberOfPages = self.images.count;
    self.pagingScrollView.contentSize = CGSizeMake(self.view.frame.size.width * self.images.count, self.view.frame.size.height);
    
    __block CGFloat x = 0;
    [[self scrollViewPages] enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
        obj.frame = CGRectOffset(obj.frame, x, 0);
        [self.pagingScrollView addSubview:obj];
        
        x += obj.frame.size.width;
    }];
    
    // fix ScrollView can not scrolling if it have only one page
    if (self.pagingScrollView.contentSize.width == self.pagingScrollView.frame.size.width) {
        self.pagingScrollView.contentSize = CGSizeMake(self.pagingScrollView.contentSize.width + 1, self.pagingScrollView.contentSize.height);
    }
}


- (void)resetScollViewPages {
    
    NSMutableArray *tmpArray = [NSMutableArray new];
    
    
    [self.images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
        
        [tmpArray addObject:[self pageViewWithImage:image]];
        
    }];
    
    
    self.scrollViewPages = [NSMutableArray arrayWithArray:tmpArray];
    
}


- (NSArray*)scrollViewPages
{

    
    if (_scrollViewPages) {
        return _scrollViewPages;
    }
    
    
    NSMutableArray *tmpArray = [NSMutableArray new];
    

    [self.images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
        
        [tmpArray addObject:[self pageViewWithImage:image]];
        
    }];

    
    _scrollViewPages = [NSMutableArray arrayWithArray:tmpArray];
    
    return _scrollViewPages;
}

- (UIView*)pageViewWithImage:(UIImage*)image
{
    UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
    imageview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    return imageview;
}




#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    self.pageControl.currentPage = scrollView.contentOffset.x / (scrollView.contentSize.width / self.images.count);
    
}




- (CGRect)frameOfPageControl
{
    CGRect orgFrame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 30);
    return CGRectOffset(orgFrame, self.pageControlOffset.x, self.pageControlOffset.y);
}

- (CGPoint)pageControlOffset
{
    if (CGPointEqualToPoint(_pageControlOffset, CGPointZero)) {
        return CGPointMake(0, -30);
    }
    return _pageControlOffset;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
